package fv;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ferdict.Outfit;

/**
 * Servlet implementation class outfits
 */
public class outfits extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public JSONObject json = new JSONObject();
	JSONArray jsonArr = new JSONArray();
	int retcnt = 25;
	String userid = null;
	String outfitid = null;
	String share = null;
	int like = -1;
	String sqlstr = null;

	private File tmpDir;
	private static final String DESTINATION_DIR_PATH = "C:\\tmp";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public outfits() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		userid = request.getParameter("token");
		outfitid = request.getParameter("id");
		if (userid == null && outfitid == null) {
			sqlstr = "select * from photos where share = 1 order by photoid desc limit "
					+ retcnt;

			jsonArr = new JSONArray();
			List<Outfit> oList = OutfitsDatabase.getOutfits();
			System.out.println("# list size = " + oList.size());
			for (Outfit outfit : oList) {
				JSONObject o = new JSONObject();
				o.put("id", outfit.getOutfitId());
				o.put("name", (outfit.getName() == null || outfit.getName()
						.length() == 0) ? "unknown" : outfit.getName());
				o.put("photo",
						request.getScheme() + "://" + request.getServerName()
								+ ":" + request.getServerPort()
								+ "/FerdictService/photos/"
								+ outfit.getPhotoUrl());
				o.put("likes", outfit.getNumLikes());
				o.put("dislikes", outfit.getNumDislikes());
				o.put("owner", (int) (Math.random() * 100));
				o.put("username", outfit.getUsername());
				o.put("share", outfit.isShare());

				jsonArr.add(o);
			}

		} else if (userid == null && outfitid != null) {
			sqlstr = "select * from photos where photoid = " + outfitid;
		} else if (userid != null && outfitid == null) {
			sqlstr = "select photoid, photoname, emailaddr, likes, dislikes, share from photos, ferdict_user where owner = "
					+ userid
					+ " and userid = owner order by photoid desc limit "
					+ retcnt;

			jsonArr = new JSONArray();
			List<Outfit> oList = OutfitsDatabase.getOutfits(userid);
			for (Outfit outfit : oList) {
				JSONObject o = new JSONObject();
				o.put("id", outfit.getOutfitId());
				o.put("name", "name-" + outfit.getName());
				o.put("photo",
						request.getScheme() + "://" + request.getServerName()
								+ ":" + request.getServerPort()
								+ "/FerdictService/photos/"
								+ outfit.getPhotoUrl());
				o.put("likes", outfit.getNumLikes());
				o.put("dislikes", outfit.getNumDislikes());
				o.put("owner", (int) (Math.random() * 100));
				o.put("username", outfit.getUsername());
				o.put("share", outfit.isShare());

				jsonArr.add(o);
			}
		}

		response.setContentType("application/json");
		response.getWriter().write(jsonArr.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	// server.xml
	// <Context path="/downloads" docBase="C:/downloads" debug="0"
	// privileged="true"/>
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		PrintWriter out = response.getWriter();
		response.setContentType("text/plain");
		out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
		out.println();

		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		/*
		 * Set the size threshold, above which content will be stored on disk.
		 */
		fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above
		 * threshold.
		 */
		fileItemFactory.setRepository(tmpDir);

		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		String name = null;
		String fieldname = "";
		String filename = "";
		try {
			/*
			 * Parse the request
			 */

			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				Object o = (FileItem) itr.next();
				FileItem item = (FileItem) o;

				if (item.isFormField() && item.getFieldName().equals("name")) {
					name = item.getString();
					System.out.println("name = " + name);
				}
				if (item.isFormField() && item.getFieldName().equals("token")) {
					userid = item.getString();
					System.out.println("userid = " + userid);

				}
				/*
				 * Handle Form Fields.
				 */
				if (!item.isFormField()) {
					Date d = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat(
							"yyyyMMddHHmmss");
					filename = sdf.format(d);
					File file = new File(DESTINATION_DIR_PATH, filename);
					item.write(file);

					// Connection conn = mysqlconn.getConn();
					// if (conn != null) {
					try {
						// Statement s = conn.createStatement();
						String sql = "insert into photos(photoname,owner) values(";
						sql = sql + filename + ", " + name + "," + userid
								+ ");";
						System.out.println(sql);

						// s.execute(sql);
						// s.close();
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
					// }
					// mysqlconn.closeConn(conn);
				}
			}
			// out.close();
		} catch (FileUploadException ex) {
			System.out.println(ex.getMessage());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

		Outfit o = new Outfit.Builder().name(URLDecoder.decode(name))
				.photo(filename).outfitId(OutfitsDatabase.id).owner(1)
				// don't care
				.share(false).username(userid).numDislikes(0).numLikes(0)
				.build();
		OutfitsDatabase.addOutfit(o);
	}

	/**
	 * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
	 */
	protected void doPut(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		userid = request.getParameter("token");
		outfitid = request.getParameter("id");
		share = request.getParameter("share");
		String like = request.getParameter("like");
		System.out.println("id = " + outfitid);
		System.out.println("like = " + like);
		System.out.println("share = " + share);
		if (share != null) {
			int shareNum = Integer.parseInt(request.getParameter("share"));
			if (shareNum == 1) {
				OutfitsDatabase.share(Integer.parseInt(outfitid));
			} else {
				OutfitsDatabase.unshare(Integer.parseInt(outfitid));
			}
		} else if (like != null) {
			int likeNum = Integer.parseInt(request.getParameter("like"));
			if (likeNum == 1) {
				sqlstr = "update photos set likes = likes + 1 where photoid = "
						+ outfitid;
				OutfitsDatabase.like(Integer.parseInt(outfitid));
			} else {
				OutfitsDatabase.dislike(Integer.parseInt(outfitid));
				sqlstr = "update photos set dislikes = dislikes + 1 where photoid = "
						+ outfitid;
			}
		}
		System.out.println(sqlstr);

		// mysqlconn sqlconn = new mysqlconn();
		// Connection conn = sqlconn.getConn();
		// try {
		// Statement s = conn.createStatement();
		// int i = s.executeUpdate(sqlstr);
		// if (i == 0)
		// System.out.println(sqlstr + "<br>succeed!");
		// else
		// System.out.println(sqlstr + "<br>failed!");
		// s.close();
		// } catch (Exception e) {
		// System.out.println(e.getMessage());
		// }
		// sqlconn.closeConn(conn);
	}

}
